<template>
    <div class="drawdetail">
        <el-card shadow="always" class="box-card">
            <el-icon size="25" @click="goBack"><Back/></el-icon> | 详情 
            <el-alert center :closable="false" title="Tips:您的图片已经发生变化，请牢记点击（取消批量管理），保存您的数据信息。" v-show="variation" type="warning" />
            <!-- 上传+批量删除按钮 -->
            <div class="btns">
                <div class="right">
                    <el-button type="primary" @click="uploadFile">上传</el-button>
                   <el-button type="primary" @click="deleteAllMethod" v-show="caozuo=='show'">批量删除</el-button>
                     <el-button type="primary" @click="caozuo = 'show'" v-show="caozuo!=='show'">批量管理</el-button>
                   <el-button type="primary" @click="cancelManayMethod" v-show="caozuo=='show'">取消批量管理</el-button>
                </div>
            </div>
            <!-- 图片列表 -->
            <ul class="list" >
                   <VueDraggableNext  
                   v-model="piclist"
                   filter=".undraggable"
                   tag="transition-group"
                   handle=".handle"
                   >
                   <transition-group>
                       <li
                           @mouseover="()=>caozuo==='show'?false:caozuo=item.id"
                           @mouseout="()=>caozuo==='show'?false:caozuo='moren'" 
                       v-for="(item, index) in piclist" :key="index" :draggable="true" style="position: relative;" :class="caozuo!=='show'?'handle undraggable':'handle'">
                           <el-image  ref="lazyImg" lazy class="vx-lazyLoad" :src="item.detailImg" :preview-src-list="[item.detailImg]"></el-image>
                           <label id="blabel" @click="">{{ item.detailName || '暂无名称' }}</label>
                           <div class="cover" @click="showDesc(item)" v-show="caozuo==item.id || caozuo==='show'">
                               <el-checkbox class="chkbox" v-show="caozuo!==item.id" v-model="item.ischked" @click.stop=""></el-checkbox>
                               <div class="picbtns">
                                   <span @click.stop="delHandle(item.id)">删除</span>
                                   <span style="float: right;margin-right: 20px;" @click.stop="setfengmian(item)">设为封面</span>
                               </div>
                           </div>
                       </li>
                   </transition-group>
               </VueDraggableNext>
        </ul>
        </el-card>
        <!-- 上传的对话框 -->
        <el-dialog v-model="uploadShow" title="提示" width="50%" :before-close="handleClose">
            <el-upload class="upload-demo" multiple :on-success="handleMethod" action="/dev-api/api/uploadimg/" :on-preview="handlePreview"
                :on-remove="handleRemove" :file-list="fileList2" list-type="picture">
                <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="uploadShow = false">取消</el-button>
                    <el-button type="primary" @click="confirmUpload">
                        确认
                    </el-button>
                </span>
            </template>
        </el-dialog>
        <!-- 修改图片名称对话框 -->
        <el-dialog v-model="editNameDialogVisiable" title="修改图片的名称" width="30%" :before-close="handleEditClose">
            <el-input v-model="name"></el-input>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="editNameDialogVisiable = false">取消</el-button>
                    <el-button type="primary" @click="confirmEdit">
                        确认
                    </el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import service from '@/utils/request.ts'
import { useRoute,useRouter } from 'vue-router';
import { VueDraggableNext } from 'vue-draggable-next'
import { Back, Search, Plus, InfoFilled } from '@element-plus/icons-vue'
const handleMethod = (obj:Object)=>{
    fileList2.value.push(obj.path)
}
// 渲染的图片列表
const piclist = ref([])
//排序是否变化
const variation = ref(false)
//监听data数据顺序变化
watch(piclist,(val,oval)=>{
    if(val.length===oval.length && val.length!==0){
        variation.value=true
    }
},{
    immediate:false,
    deep:false
})

const router = useRouter()
const goBack = ()=>{
    router.back()
}
//取消批量管理时
const cancelManayMethod =async ()=>{
    caozuo.value = 'moren'
    const sortOrderData = piclist.value.map((item,index)=>{
        return {[item.id]:index+1}
    })
    const {code} = await service.post(`/api/draw/detailImgSort`,sortOrderData)
    if(code===200){
        variation.value=false
        ElMessage('保存成功！')
    }
}
//批量删除
const deleteAllMethod =async ()=>{
    const ids = piclist.value.filter(item=>item.ischked).map(item=>item.id)
    if(ids.length<=0){
        return ElMessage('请选择删除的对象！')
    }
    const {code,msg} =  await service.post(`/api/draw/detailDel`,{ids})
    if(code===200){
        ElMessage(msg)
        getDateList()
    }
}

// 上传的图片列表
const fileList2 = ref([])
const route = useRoute()
const getDateList = async()=>{
    const {code,data} =  await service.get(`/api/draw/detailShow?id=${route.query.id}`)
    if(code===200){
        piclist.value = data
    }
}
const updateId = ref('')
const showDesc = (row:Object)=>{
    updateId.value = row.id
    name.value = row.detailName
    editNameDialogVisiable.value=true
}

onMounted(()=>{
    getDateList()
})
// 控制批量上传对话框
let uploadShow = ref(false)
// 控制批量操作按钮（删除/设置为封面）的显示和隐藏
let caozuo = ref('')
// 存储要删除的元素
let dellist = ref([])
// 控制修改图片的对话框
let editNameDialogVisiable=ref(false)
// 修改后的图片名称
let name=ref('')

// 显示上传对话框
let uploadFile = () => {
    uploadShow.value = true
}

// 上传对话框关闭前
let handleClose = () => {
    uploadShow.value = false
}

// 确定上传
let confirmUpload =async () => {
    console.log(fileList2.value, '执行上传操作');
    for (const iterator of fileList2.value) {
        await service.post(`/api/draw/detailAdd`,{version_imgId_id:route.query.id,detailImg:iterator})
    }
    getDateList()
    uploadShow.value = false
}

// 移除上传的图片
let handleRemove = (file: any, fileList: any) => {
    console.log(file, fileList);
}

// 图片预览
let handlePreview = (file: any) => {
    console.log(file);
}

// 删除图片操作
let delHandle = (id:Number) => {
    ElMessageBox.confirm(
    '确定删除？此消息无法恢复',
    '删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
        const {code} =  await service.delete(`/api/draw/detailDel?id=${id}`)
        if(code!==200){
            return
        }
        getDateList()
      ElMessage({
        type: 'success',
        message: '删除成功',
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}

// 设置为封面
let setfengmian=async (item)=>{
    const {code,msg} =  await service.post(`/api/draw/versionSet`,{id:route.query.id,versionImg:item.detailImg})
    if(code===200){
        ElMessage('设置封面成功')
    }
}


// 修改图片
let confirmEdit=async ()=>{
    const {code,msg} = await service.post(`/api/draw/detailSet`,{id:updateId.value,detailName:name.value})
    if(code===200){
        ElMessage(msg)
        getDateList()
    }
    editNameDialogVisiable.value=false
}

// 关闭修改图片名称的对话框
let handleEditClose=()=>{
    editNameDialogVisiable.value=false
}
</script>

<style lang="scss" scoped>

#blabel{
    text-align: center;
}
.box-card {
    width: 96%;
    height: 90%;
    margin: 0 auto;
    margin-top: 1rem;
}

.btns {
    height: 4rem;
    line-height: 4rem;
}

.right {
    float: right;
}

.el-button {
    box-sizing: border-box;
    width: 6rem;
    height: 2rem;
    font-size: 0.6rem;
}

ul li {
    height: 14rem;
    list-style: none;
    display: inline-block;
    margin: 0 0.7rem;
    margin-bottom: 1rem;
}

.list {
    margin-top: 1rem;
}

.list li .el-image {
    width: 10rem;
    height: 12rem;
}

.list li label {
    display: block;
    width: 10rem;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.picbtns {
    position: absolute;
    bottom: 10px;
    color: white;
    font-size: 12px;
    padding-left: 20px;
    width: 100%;
}

.chkbox {
    margin-left: 10px;
    margin-top: 10px;
}

.cover {
    width: 100%;
    height: 12rem;
    background-color: rgba(0, 0, 0, 0.2);
    position: absolute;
    top: 0;
    left: 0;
}
//拖拽样式
.draggable{
  position: relative;
  width: 400px;
  height: 400px;
  border: 1px solid red;
  left: 50%;
  transform: translateX(-50%);
}
.item{
  box-sizing: border-box;
  width: 100%;
  padding: 7px;
  border: 1px solid #ccc;
  margin-bottom: 10px;
  cursor: pointer;
}
.ghostClass{
  border: 2px solid yellow !important;
}
.hostClass{
  background-color: pink !important;
}
.dragClass{
  font-size: 24px;
}
</style>